package com.macro.mall.tiny.modules.pms.controller;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.modules.pms.model.PmsActivationCode;
import com.macro.mall.tiny.modules.pms.model.PmsActivationCodeUse;
import com.macro.mall.tiny.modules.pms.service.PmsActivationCodeService;
import com.macro.mall.tiny.modules.pms.service.PmsActivationCodeUseService;
import com.macro.mall.tiny.modules.ums.model.UmsAdmin;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsMemberService;
import com.macro.mall.tiny.security.util.AdminContext;
import com.macro.mall.tiny.security.util.AdminHolder;
import com.macro.mall.tiny.security.util.MemberContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 激活码表 前端控制器
 * </p>
 *
 * @author tyrone
 * @since 2025-03-02
 */
@RestController
@RequestMapping("/pms/pmsActivationCode")
@Api(tags = "PmsActivationCodeController", description = "激活码管理")
@Tag(name = "PmsActivationCodeController", description = "激活码管理")
public class PmsActivationCodeController {


    @Autowired
    private PmsActivationCodeService pmsActivationCodeService;
    @Autowired
    private PmsActivationCodeUseService pmsActivationCodeUseService;

    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/generate")
    @ApiOperation(value = "生成激活码")
    public CommonResult<PmsActivationCode> generate(@RequestParam(required = false, defaultValue = "365") Integer duration) {
//        UmsAdmin umsAdmin = AdminContext.getHolder().get();
//        if (umsAdmin == null) {
//            return CommonResult.failed("请先登录");
//        }
        Long id = IdUtil.getSnowflake().nextId();
        while (Boolean.TRUE.equals(redisTemplate.opsForSet().isMember("activation_code", id))) {
            id = IdUtil.getSnowflake().nextId();
        }

        PmsActivationCode pmsActivationCode = new PmsActivationCode();
        pmsActivationCode.setCode(id.toString());
        pmsActivationCode.setDuration(duration);
        pmsActivationCodeService.save(pmsActivationCode);

        return CommonResult.success(pmsActivationCode);
    }


    @GetMapping("/use")
    @ApiOperation(value = "使用激活码")
    public CommonResult<Void> use(@RequestParam String code) {
        UmsMember member = MemberContext.getMember();
        if (member == null) {
            return CommonResult.failed("请先登录");
        }
        PmsActivationCode pmsActivationCode = pmsActivationCodeService.getOne(new QueryWrapper<PmsActivationCode>().eq("code", code));
        if (pmsActivationCode == null) {
            return CommonResult.failed("激活码不存在");
        }
        if (pmsActivationCode.getStatus() == 1) {
            return CommonResult.failed("激活码已使用");
        }
        if (pmsActivationCode.getStatus() == 2) {
            return CommonResult.failed("激活码无效");
        }
        if (pmsActivationCode.getDuration() != null && pmsActivationCode.getDuration() > 0) {
            Date newVipExpireTime = member.getVipExpireTime() == null ? new Date() : member.getVipExpireTime();
            member.setVipExpireTime(DateUtil.offsetDay(newVipExpireTime, pmsActivationCode.getDuration()));
            member.setVip(1);
            umsMemberService.updateById(member);
        }
        pmsActivationCode.setStatus(1);
        pmsActivationCode.setActivationTime(new Date());
        pmsActivationCodeService.updateById(pmsActivationCode);
        PmsActivationCodeUse pmsActivationCodeUse = new PmsActivationCodeUse();
        pmsActivationCodeUse.setCode(pmsActivationCode.getCode());
        pmsActivationCodeUse.setMemberId(member.getId());
        pmsActivationCodeUse.setActivationTime(new Date());
        pmsActivationCodeUse.setCreateTime(new Date());
        pmsActivationCodeUseService.save(pmsActivationCodeUse);
        redisTemplate.opsForSet().add("activation_code", code);
        return CommonResult.success(null);
    }

    @ApiOperation(value = "后台分页查询激活码")
    @PostMapping("/page")
    public CommonResult<Page<PmsActivationCode>> page(@RequestBody PmsActivationCode code) {
//        UmsAdmin umsAdmin = AdminContext.getHolder().get();
//        if (umsAdmin == null) {
//            return CommonResult.failed("请先登录");
//        }
        Page<PmsActivationCode> page = new Page<>(code.getPageNum(), code.getPageSize(), Boolean.TRUE);
        LambdaQueryWrapper<PmsActivationCode> wrap = new LambdaQueryWrapper<>();
        if (code.getStatus() != null) {
            wrap.eq(PmsActivationCode::getStatus, code.getStatus());
        }
        if (code.getId() != null) {
            wrap.eq(PmsActivationCode::getId, code.getId());
        }
        if (code.getActivationTimeStart() != null) {
            wrap.ge(PmsActivationCode::getActivationTime, code.getActivationTimeStart());
        }
        if (code.getActivationTimeEnd() != null) {
            wrap.le(PmsActivationCode::getActivationTime, code.getActivationTimeEnd());
        }
        if (code.getCreateTimeStart() != null) {
            wrap.ge(PmsActivationCode::getCreateTime, code.getCreateTimeStart());
        }
        if (code.getCreateTimeEnd() != null) {
            wrap.le(PmsActivationCode::getCreateTime, code.getCreateTimeEnd());
        }
        if (StringUtils.isNoneEmpty(code.getCode())) {
            wrap.like(PmsActivationCode::getCode, code.getCode());
        }
        wrap.orderByDesc(PmsActivationCode::getId);
        return CommonResult.success(pmsActivationCodeService.page(page, wrap));
    }

    @GetMapping("/update")
    @ApiOperation(value = "更新激活码")
    public CommonResult<Void> update(@RequestParam Integer status, @RequestParam Integer id) {
        pmsActivationCodeService.update(new UpdateWrapper<>(new PmsActivationCode()).eq("id", id).set("status", status));
        return CommonResult.success(null);
    }


    public static void main(String[] args) {
        System.out.println(IdUtil.getSnowflake().nextId());
    }

}

